﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using ElectronicCommerce.Framework.Data.Utility;
using ElectronicCommerce.Framework.Payment.Contract.DataContract;
using ElectronicCommerce.Framework.Payment.Contract.DataContract.Common;
using ElectronicCommerce.Framework.Payment.Contract.DataContract.History;
using ElectronicCommerce.Framework.Payment.Data.Interfaces;
using ElectronicCommerce.Framework.Utility;

namespace ElectronicCommerce.Framework.Payment.Data.SqlServer
{
    public class SqlRefundHistoryRepository : IRefundHistoryRepository
    {
        #region SQL

        private const string SQL_RefundHistory_INSERT = @"
            INSERT INTO dbo.PaymentRefundHistory(
                SOID, OutSOID, RequestRefundAmount, FactRefundAmount, CurrencyCode, 
                ReasonDesc, RefundDate, ResultType, ResultMessage)
            VALUES(
                @SOID, @OutSOID, @RequestRefundAmount, @FactRefundAmount, @CurrencyCode,
                @ReasonDesc, @RefundDate, @ResultType, @ResultMessage)
        ";

        private const string SQL_RefundHistory_SELECT = @"
            SELECT TransactionNumber, SOID, OutSOID, RequestRefundAmount, FactRefundAmount, CurrencyCode,
                ReasonDesc, RefundDate, ResultType, ResultMessage
            FROM dbo.PaymentRefundHistory(NOLOCK)
            WHERE SOID=@SOID
        ";

        private const string SQL_RefundHistory_SELECT_LastDate = @"
            SELECT TOP 1 RefundDate FROM dbo.PaymentRefundHistory(NOLOCK) 
            WHERE SOID=@SOID 
            ORDER BY RefundDate DESC
        ";

        #endregion


        /// <summary>
        /// 记录退款日志
        /// </summary>
        /// <param name="request"></param>
        /// <param name="result"></param>
        public void InsertRefundHistory(RefundRequest request, RefundResult result)
        {
            SqlParameter[] sqlParameters = new SqlParameter[]{
                new SqlParameter("@SOID", request.RefundInfo.SOID),
                new SqlParameter("@OutSOID", result.OutSOID),
                new SqlParameter("@RequestRefundAmount", request.RefundInfo.RefundAmount),
                new SqlParameter("@FactRefundAmount", result.RefundAmount),
                new SqlParameter("@CurrencyCode", request.RefundInfo.CurrencyCode.ToString()),
                new SqlParameter("@ReasonDesc", request.RefundInfo.ReasonDesc),
                new SqlParameter("@RefundDate", request.RefundInfo.RefundDate),
                new SqlParameter("@ResultType", (int)result.ResultType),
                new SqlParameter("@ResultMessage", result.ResultMessage)
            };

            SqlHelper.ExecuteNonQuery(ConnectionStrings.Payment, CommandType.Text,
                SQL_RefundHistory_INSERT, sqlParameters);
        }

        /// <summary>
        /// 获取退款历史记录
        /// </summary>
        /// <param name="soID"></param>
        /// <returns></returns>
        public List<RefundHistory> GetRefundHistoryList(string soID)
        {
            List<RefundHistory> refundHistoryList = new List<RefundHistory>();

            SqlParameter[] sqlParameters = new SqlParameter[] {
                new SqlParameter("@SOID", soID)            
            };

            using (IDataReader dr = SqlHelper.ExecuteReader(ConnectionStrings.Payment, CommandType.Text,
                SQL_RefundHistory_SELECT, sqlParameters))
            {
                while (dr.Read())
                {
                    RefundHistory refundHistory = new RefundHistory();
                    refundHistory.TransactionNumber = Convert.ToInt32(dr["TransactionNumber"]);
                    refundHistory.SOID = Convert.ToString(dr["SOID"]);
                    refundHistory.OutSOID = Convert.ToString(dr["OutSOID"]);
                    refundHistory.RequestRefundAmount = Convert.ToDecimal(dr["RequestRefundAmount"]);
                    refundHistory.FactRefundAmount = Convert.ToDecimal(dr["FactRefundAmount"]);
                    refundHistory.CurrencyCode = (CurrencyCode)Enum.Parse(typeof(CurrencyCode), Convert.ToString(dr["CurrencyCode"]));
                    refundHistory.ReasonDesc = Convert.ToString(dr["ReasonDesc"]);
                    refundHistory.RefundDate = Convert.ToDateTime(dr["RefundDate"]);
                    refundHistory.ResultType = (RefundResultType)Convert.ToInt32(dr["ResultType"]);
                    refundHistory.ResultMessage = Convert.ToString(dr["ResultMessage"]);

                    refundHistoryList.Add(refundHistory);
                }
            }

            return refundHistoryList;
        }

        /// <summary>
        /// 获取某个订单相关的最近退款时间
        /// </summary>
        /// <param name="soID"></param>
        /// <returns></returns>
        public DateTime GetLastRefundDate(string soID)
        {
            DateTime lastDate = DateTimeHelper.MinValue;

            SqlParameter[] sqlParameters = new SqlParameter[] {
                new SqlParameter("@SOID", soID)            
            };

            lastDate = Convert.ToDateTime(SqlHelper.ExecuteScalar(ConnectionStrings.Payment, CommandType.Text,
                SQL_RefundHistory_SELECT_LastDate, sqlParameters));

            if (lastDate < DateTimeHelper.MinValue)
                lastDate = DateTimeHelper.MinValue;

            return lastDate;
        }
    }
}
